package wili.attrMapping.file;

import java.io.File;
import java.net.MalformedURLException;
import java.util.List;
import java.util.function.Function;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import wili.attrMapping.core.Att9;
import wili.attrMapping.core.AttsFile;
import wili.c.Ca;
import wili.c.File9a;
import wili.json.xml.XmlTag;

/**
 * File which name ends with ".json"
 */
public class XmlFile implements AttsFile {
	public final File file;
	public XmlTag root;

	public String toString() {
		return file.getName();
	}

	public void print(int opt) {
		if (opt < 0)
			return;
		StringBuilder sb = new StringBuilder();
		sb.append("\n==============jsonFile: " + file.getName());
		sb.append(root.element.asXML());
		Ca.log(1, sb);
	}

	public static XmlFile newInst(File file) {
		XmlFile ret;
		try {
			ret = new XmlFile(file);
			return ret;
		} catch (MalformedURLException | DocumentException e) {
			e.printStackTrace();
			return null;
		}
	}

	private XmlFile(File file) throws MalformedURLException, DocumentException {
		this.file = file;
		SAXReader reader = new SAXReader();
		Document doc = reader.read(file.toURI().toURL());
		this.root = new XmlTag(doc.getRootElement());
	}

	public String refreshJsonSt() {
		return root.element.asXML();
	}

	public List<XmlTag> findNodesByPath(String xpath) {
		try {
			//xpath = "//" + xpath;
			List<Node> toList = this.root.element.selectNodes(xpath);
			List<XmlTag> lis = toList.stream().map(nod -> new XmlTag(nod)).toList();
			return lis;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// @Override
	public void saveToFile(File toFile, Function<String, String> fun) {
		if (toFile == null)
			toFile = this.file;
		String retSt = this.refreshJsonSt();
		if (fun != null)
			retSt = fun.apply(retSt);
		if (false)
			retSt = retSt.replaceAll("\\$\\{ObjType\\}\\s*===\\s*(-?\\d+)", "\\$\\{ObjType\\} === '$1'");
		File9a.str2file(retSt, toFile, -1);
		if (Att9.DEBUG)
			Ca.log(1, "\n JsonFile.saveToFile: " + toFile.getName());
	}

	// @Override
	public File file() {
		return this.file;
	}

	@Override
	public int[] getUpdateTimes() {
		return null;
	}
}
